package cn.itsource.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.internet.MimeMessage;
import java.io.File;

@Component
public class MailSendComponent {
    //从application.yml文件中读取信息。意思：从配置文件中读取一个属性名叫：spring.mail.username的值
    @Value("${spring.mail.username}")
    private String fromEmail;

    @Autowired //邮箱发送的api
    private JavaMailSender javaMailSender;
    public void sendSimpleMail(String mailTo,String mailSubject,String mailContent){
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        //设置发送人
        mailMessage.setFrom(fromEmail);
        //邮件主题
        mailMessage.setSubject(mailSubject);
        //邮件内容
        mailMessage.setText(mailContent);
        //收件人
        mailMessage.setTo(mailTo);

        javaMailSender.send(mailMessage);
    }

    public void sendFuza() throws Exception{
        //1. 创建复杂邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //2. 发送复杂邮件的工具类
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
        //设置邮件的发送方
        helper.setFrom("286129277@qq.com");
        //邮箱的主题（标题）
        helper.setSubject("新型冠状病毒防护指南");
        //复杂邮件发送，可以发送html代码
        helper.setText("<h1>新型冠状病毒防护守则</h1>"+
                "<img src='http://47.95.117.210:8888/group1/M00/00/30/rBE3kWDED6eAGsqWAADWxjhW8FE176.jpg' />",true);
        //添加附件
        helper.addAttachment("美女.jpg",new File("d:\\11.jpg"));
        helper.addAttachment("sql文件", new File("d:\\test.sql"));
        //收件人
        helper.setTo("286129277@qq.com");

        javaMailSender.send(mimeMessage);
    }
}
